package com.gzdict.common.utils

import android.util.Log
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors


/**
 * Created by shang
 * 日志工具类
 */
object LogUtil {
    private val TAG = "SHANG"
    private val TOP_BORDER =    "╔═══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════"
    private val LEFT_BORDER = "║ "
    private val BOTTOM_BORDER = "╚═══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════"
    private var debug: Boolean = true//是否打印log
    private var savesd: Boolean = false//是否存log到sd卡
    private val CHUNK_SIZE = 200 //设置字节数
    private var logDir = ""//设置文件存储目录
    private var logSize = 2 * 1024 * 1024L//设置log文件大小 k
    private val execu: ExecutorService = Executors.newFixedThreadPool(1)

    init {
//        initLogFile()
    }

    fun Any.logi(){
        i(msg = this.toString())
    }
    fun Any.loge(){
        e(msg = this.toString())
    }

    fun v( msg: String,tag: String? = TAG) = debug.debugLog(tag, msg, Log.VERBOSE)
    fun d( msg: String,tag: String? = TAG) = debug.debugLog(tag, msg, Log.DEBUG)
    fun i( msg: String,tag: String? = TAG) = debug.debugLog(tag, msg, Log.INFO)
    fun w( msg: String,tag: String? = TAG) = debug.debugLog(tag, msg, Log.WARN)
    fun e( msg: String,tag: String? = TAG) = debug.debugLog(tag, msg, Log.ERROR)

    private fun targetStackTraceMSg(): String {
        val targetStackTraceElement = getTargetStackTraceElement()
        if (targetStackTraceElement != null) {
            return "at ${targetStackTraceElement.className}.${targetStackTraceElement.methodName}(${targetStackTraceElement.fileName}:${targetStackTraceElement.lineNumber})"
        } else {
            return ""
        }
    }

    private fun getTargetStackTraceElement(): StackTraceElement? {
        var targetStackTrace: StackTraceElement? = null
        var shouldTrace = false
        val stackTrace = Thread.currentThread().stackTrace
        for (stackTraceElement in stackTrace) {
            val isLogMethod = stackTraceElement.className == LogUtil::class.java.name
            if (shouldTrace && !isLogMethod) {
                targetStackTrace = stackTraceElement
                break
            }
            shouldTrace = isLogMethod
        }
        return targetStackTrace
    }


//    private fun initLogFile() {
//        logDir = "${FileUtils.getRootDir()}/hotapk.cn"
//        FileUtils.mkDir(logDir)
//    }

    private fun Boolean.debugLog(tag: String?, msg: String, type: Int) {
        if (!this) {
            return
        }
        val newMsg = msgFormat(msg)
//        savesd.saveToSd("${SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).format(Date())}\n${targetStackTraceMSg()}", msg)
        when (type) {
            Log.VERBOSE -> Log.v(tag, newMsg)
            Log.DEBUG -> Log.d(tag, newMsg)
            Log.INFO -> Log.i(tag, newMsg)
            Log.WARN -> Log.w(tag, newMsg)
            Log.ERROR -> Log.e(tag, newMsg)
        }

    }

    private fun msgFormat(msg: String): String {
        val bytes: ByteArray = msg.toByteArray()
        val length = bytes.size
        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.sss", Locale.CHINA)
        var newMsg = "\n$TOP_BORDER \n$LEFT_BORDER\t${targetStackTraceMSg()}\n"

        newMsg += msg

        newMsg += "\n$LEFT_BORDER\t${sdf.format(Date())}\n$BOTTOM_BORDER\n"
        return newMsg

    }

//    private fun Boolean.saveToSd(tag: String, msg: String) {
//        if (!this) {
//            return
//        }
//        execu.submit({
//            val data = SimpleDateFormat("yyyy-MM-dd", Locale.US).format(Date())
//            var files = FileUtils.sortByTime(File(logDir))?.filter { it -> it.name.contains(data) }
//            var filepath: String
//            if (files != null && files.isNotEmpty()) {
//                val length: Long = FileUtils.getLeng(files[0])
//                if (length > logSize) {
//                    val id = files[0].name.replace("${data}_", "").replace(".log", "").toInt() + 1
//                    filepath = "$logDir/${data}_$id.log"
//                    FileUtils.creatFile(filepath)
//                } else {
//                    filepath = files[0].absolutePath
//                }
//            } else {
//                filepath = "$logDir/${data}_1.log"
//                FileUtils.creatFile(filepath)
//            }
//            FileUtils.appendText(File(filepath), "\r\n$tag\n$msg")
//        })
//
//    }


    /**
     * 是否打印log输出
     * @param debug
     */
    fun debug(debug: Boolean): LogUtil {
        LogUtil.debug = debug
        return this
    }

    /**
     * 是否保存到sd卡
     * @param savesd
     */
    fun saveSd(savesd: Boolean): LogUtil {
        LogUtil.savesd = savesd
        return this
    }

    /**
     * 设置每个log的文件大小
     * @param logSize 文件大小 byte
     */
    fun logSize(logSize: Long): LogUtil {
        LogUtil.logSize = logSize
        return this

    }

    /**
     * 设置log文件目录
     * @param logDir 文件目录
     */
    fun logDir(logDir: String): LogUtil {
        LogUtil.logDir = logDir
        return this
    }
}

